package com.chaodows.commons.dto.result;

import io.swagger.annotations.ApiModel;
import lombok.Data;

import java.io.Serializable;

/**
 * ============================
 *
 * @Author pengzhichao
 * @Description //TUDO $
 * @Date 2021/7/30 18:38
 * @Version 1.0
 * ============================
 **/
@Data
@ApiModel(value = "ResponseDataDTO", description = "json输出数据格式")
public class ResponseDataDTO<T> implements Serializable {

    private static final long serialVersionUID = -5916495024828261453L;

    public static final ResponseDataDTO<Void> SUCCESS = buildSuccess();

    /**
     * 状态
     */
    private String status = Status.STATUS_SUCCESS;

    /**
     * JSON码
     */
    private Integer code;

    /**
     * 信息
     */
    private String msg;

    /**
     * JSON返回类型
     */
    private T data;

    /**
     * 创建成功的JSON串
     * @param t
     * @param <T>
     * @return
     */
    public static <T> ResponseDataDTO<T> buildSuccess(T t){
        ResponseDataDTO<T> result = new ResponseDataDTO<>();
        result.setCode(ResultCode.SUCCESS.code());
        result.setData(t);
        result.setStatus(Status.STATUS_SUCCESS);
        result.setMsg(ResultCode.SUCCESS.message());
        return result;
    }

    /**
     * 创建基本的初始的成功JSON串
     * @param <T>
     * @return
     */
    public static <T> ResponseDataDTO<T> buildSuccess(){
        return buildSuccess(null);
    }

    /**
     * 输出默认的失败请求
     * @param code
     * @param <T>
     * @return
     */
    public static <T> ResponseDataDTO<T> buildFail(ResultCode code){
        return buildFail(null,ResultCode.FAIL.message());
    }

    /**
     * 自定义失败输出JSON对象
     * @param t
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseDataDTO<T> buildFail(T t,String msg){
        ResponseDataDTO result = new ResponseDataDTO();
        result.setCode(ResultCode.FAIL.code());
        result.setStatus(Status.STATUS_FAIL);
        result.setMsg(msg);
        result.setData(t);
        return result;
    }

    /**
     * 自定义错误数据JSON对象
     * @param code
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseDataDTO<T> buildError(ResultCode code,String msg){
        ResponseDataDTO result = new ResponseDataDTO();
        result.setMsg(msg);
        result.setData(null);
        result.setStatus(Status.STATUS_ERROR);
        result.setCode(code.code());
        return result;
    }

    /**
     * 输出初始服务错误
     * @param <T>
     * @return 返回初始的服务错误
     */
    public static <T> ResponseDataDTO<T> buildError(){
        return buildError(ResultCode.SERVICE_INNER_ERROR,ResultCode.SERVICE_INNER_ERROR.message());
    }
}
